//
//  AddressBook.m
//  HomeworkOfAddressBook
//
//  Created by Scott on 16/4/28.
//  Copyright © 2016年 Scott. All rights reserved.
//

#import "AddressBook.h"
#import "Contact.h"


@interface AddressBook ()

@property (nonatomic, retain) NSMutableDictionary *mDic;

@end


@implementation AddressBook




- (void)addContact:(Contact *)contact {

   NSMutableArray *mArr = [self.mDic objectForKey:contact.group];
    
    
    if (mArr == nil) {
        
      mArr = [NSMutableArray array];
        
        [mArr addObject:contact];
        
        [self.mDic setObject:mArr forKey:contact.group];
    } else {
        
        [mArr addObject:contact];
        
        
    }

}

/** 返回字符串首字母且大写. */
- (NSString *)firstCharactor:(NSString *)string {
    
    return [[string substringToIndex:1] uppercaseString];
}


- (void)deleteContactForName:(NSString *)name {
    
    NSMutableArray *mArr = [self.mDic objectForKey:[self firstCharactor:name]];

    NSMutableArray *arrOfTemp = [NSMutableArray array];
    
    // 遍历数组
    for (Contact *con in mArr) {
        
        if ([con.name isEqualToString:name]) {
            
            [arrOfTemp addObject:con];
        }
    }
    
    // 删除temp数组包含的所有对象.
    [mArr removeObjectsInArray:arrOfTemp];
    
}

- (NSArray<Contact *> *)showAllContactForGroup:(NSString *)group {
    
    
    NSMutableArray *mArr = [self.mDic objectForKey:[self firstCharactor:group]];
    
    // 按照联系人姓名升序排序
    NSArray *arrOfSort = [mArr sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        
        Contact *con1 = (Contact *)obj1;
        Contact *con2 = (Contact *)obj2;
        
        return [con1.name compare:con2.name];

    }];
    

    return arrOfSort;
}






@end
